<template>
  <ContentWrap>
    <!-- 顶部导航 -->
    <div class="header-navigation flex items-center justify-center mb-20px">
      <el-button @click="prevWeek" type="primary" plain :disabled="loading" class="mr-20px"
        >上一个</el-button
      >
      <div class="flex items-center mx-20px gap-10px">
        <div class="text-20px font-bold"
          >{{ currentWeeklyMenu.weekYear }}年第{{ currentWeeklyMenu.weekNumber }}周</div
        >
        <div class="text-14px text-gray-500 mt-2px">
          {{ formatDate(currentWeeklyMenu.weekStartDate) }} 至
          {{ formatDate(currentWeeklyMenu.weekEndDate) }}
        </div>
      </div>
      <el-button @click="nextWeek" type="primary" plain :disabled="loading" class="ml-20px"
        >下一个</el-button
      >
    </div>

    <!-- Tabs切换 -->
    <el-tabs v-model="activeTab" class="mb-20px">
      <el-tab-pane label="周食谱" name="recipe" />
      <el-tab-pane label="食材采购" name="shopping" />
      <el-tab-pane label="带量统计" name="quantity" />
      <el-tab-pane label="营养统计" name="nutrition" />
      <el-tab-pane label="过敏统计" name="allergy" />
    </el-tabs>

    <!-- 周食谱内容 -->
    <WeeklyRecipeTable
      v-if="activeTab === 'recipe'"
      v-model:loading="loading"
      :current-weekly-menu="currentWeeklyMenu"
      ref="weeklyRecipeTableRef"
    />

    <!-- 食材采购内容 -->
    <ShoppingTable
      v-else-if="activeTab === 'shopping'"
      v-model:loading="loading"
      :current-weekly-menu="currentWeeklyMenu"
      ref="shoppingTableRef"
    />

    <!-- 带量统计内容 -->
    <QuantityTable
      v-else-if="activeTab === 'quantity'"
      v-model:loading="loading"
      :current-weekly-menu="currentWeeklyMenu"
      ref="quantityTableRef"
    />

    <!-- 营养统计内容 -->
    <NutritionTable
      v-else-if="activeTab === 'nutrition'"
      v-model:loading="loading"
      :current-weekly-menu="currentWeeklyMenu"
      ref="nutritionTableRef"
    />

    <!-- 过敏统计内容 -->
    <AllergyTable
      v-else-if="activeTab === 'allergy'"
      v-model:loading="loading"
      :current-weekly-menu="currentWeeklyMenu"
      ref="allergyTableRef"
    />

    <!-- 其他Tab内容预留 -->
    <div v-loading="loading" v-else>
      <el-empty :description="`${activeTabName}内容待开发`" />
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { useMessage } from '@/hooks/web/useMessage'
import { formatDate } from '@/utils/formatTime'
import { RecipeMenusWeeklyApi } from '@/api/school/recipe/menusWeekly'
import WeeklyRecipeTable from './components/WeeklyRecipeTable.vue'
import ShoppingTable from './components/ShoppingTable.vue'
import QuantityTable from './components/QuantityTable.vue'
import NutritionTable from './components/NutritionTable.vue'
import AllergyTable from './components/AllergyTable.vue'

defineOptions({ name: 'WeeklyRecipe' })

const route = useRoute()

const message = useMessage()

// 数据加载状态
const loading = ref(false)

// 周食谱数据
const weeklyMenuList = ref<any[]>([]) // 存储分页获取的所有周食谱
const currentWeeklyMenuIndex = ref(-1) // 当前显示的周食谱在列表中的索引
const weeklyMenuListTotal = ref(0)
// 分页参数
const pageParams = reactive({
  pageNo: 1,
  pageSize: 100
})

// 组件引用
const weeklyRecipeTableRef = ref()
const shoppingTableRef = ref()
const quantityTableRef = ref()
const nutritionTableRef = ref()
const allergyTableRef = ref()

// 当前显示的周食谱数据
const currentWeeklyMenu = computed(() => {
  if (
    weeklyMenuList.value.length > 0 &&
    currentWeeklyMenuIndex.value < weeklyMenuList.value.length
  ) {
    return weeklyMenuList.value[currentWeeklyMenuIndex.value] || {}
  }
  return {}
})

// Tabs相关
const activeTab = ref('recipe')
const activeTabName = computed(() => {
  const tabs: Record<string, string> = {
    recipe: '周食谱',
    shopping: '食材采购',
    quantity: '带量统计',
    nutrition: '营养统计',
    allergy: '过敏统计'
  }
  return tabs[activeTab.value] || ''
})

// 上一周
const prevWeek = async () => {
  if (currentWeeklyMenuIndex.value > 0) {
    // 切换到当前页的上一个周食谱
    currentWeeklyMenuIndex.value--
  } else if (pageParams.pageNo > 1) {
    // 切换到上一页的最后一个周食谱
    pageParams.pageNo--
    await loadWeeklyMenuList(() => {
      currentWeeklyMenuIndex.value = weeklyMenuList.value.length - 1
    })
  } else {
    message.warning('已经是第一个周食谱了')
  }
}

// 下一周
const nextWeek = async () => {
  if (currentWeeklyMenuIndex.value < weeklyMenuList.value.length - 1) {
    // 切换到当前页的下一个周食谱
    currentWeeklyMenuIndex.value++
  } else {
    if (weeklyMenuListTotal.value <= pageParams.pageNo * pageParams.pageSize) {
      message.warning('已经是最后一个周食谱了')
      return
    }
    // 切换到下一页的第一个周食谱
    pageParams.pageNo++
    await loadWeeklyMenuList(() => {
      currentWeeklyMenuIndex.value = 0
    })
    if (weeklyMenuList.value.length === 0) {
      // 如果没有下一页数据，恢复页码
      pageParams.pageNo--
      currentWeeklyMenuIndex.value = weeklyMenuList.value.length - 1
      message.warning('已经是最后一个周食谱了')
    }
  }
}

// 加载周食谱列表（用于分页导航）
const loadWeeklyMenuList = async (callback?: any) => {
  loading.value = true
  try {
    const res = await RecipeMenusWeeklyApi.getRecipeMenusWeeklyPage(pageParams)
    weeklyMenuListTotal.value = res.total || 0
    if (res?.list?.length) {
      weeklyMenuList.value = res.list
    }
    callback?.()
  } catch (err) {
    message.error('加载周食谱列表失败')
  } finally {
    loading.value = false
  }
}

// 监听路由变化
watch(
  () => route.query.menuId,
  async (newMenuId) => {
    if (newMenuId) {
      // 根据menuId查找在列表中的位置
      if (!weeklyMenuList?.value?.length) {
        const { pageNo, pageSize }: any = route.query
        pageParams.pageNo = pageNo || 1
        pageParams.pageSize = pageSize || 100
        await loadWeeklyMenuList(() => {
          const menuIndex = weeklyMenuList?.value.findIndex(
            (item) => item.menuId === Number(newMenuId)
          )
          currentWeeklyMenuIndex.value = menuIndex > -1 ? menuIndex : -1
        })
      }
    }
  },
  { immediate: true }
)

// 监听activeTab变化，当切换到对应tab时重新加载数据
watch(
  () => activeTab.value,
  async (newTab) => {
    if (newTab === 'recipe' && weeklyRecipeTableRef.value) {
      await weeklyRecipeTableRef.value.loadWeeklyMenuDetail(currentWeeklyMenu.value.menuId)
    } else if (newTab === 'shopping' && shoppingTableRef.value) {
      await shoppingTableRef.value.loadShoppingData(currentWeeklyMenu.value.menuId)
    } else if (newTab === 'quantity' && quantityTableRef.value) {
      await quantityTableRef.value.loadQuantityData(currentWeeklyMenu.value.menuId)
    } else if (newTab === 'nutrition' && nutritionTableRef.value) {
      await nutritionTableRef.value.loadNutritionData(currentWeeklyMenu.value.menuId)
    } else if (newTab === 'allergy' && allergyTableRef.value) {
      await allergyTableRef.value.loadAllergyData(currentWeeklyMenu.value.menuId)
    }
  }
)
</script>

<style lang="scss" scoped>
.header-navigation {
  padding: 6px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
